package inet.app.view.activity;

import inet.app.GCMIntentService;
import inet.app.R;
import inet.app.common.XoSoConstants;
import inet.app.controller.connect.JsonParser;
import inet.app.controller.connect.MasterConnector;
import inet.app.controller.database.DBConfig;
import inet.app.controller.database.DatabaseManager;
import inet.app.controller.parser.Parser_Slave_Resp;
import inet.app.controller.request.Request;
import inet.app.controller.request.Request_Format;
import inet.app.model.object.KqGiaiRegion;
import inet.app.model.object.Slave;
import inet.app.model.util.BitmapLargeManager;
import inet.app.model.util.BitmapLargeManager.LoadBitmapListener;
import inet.app.model.util.DateProc;
import inet.app.model.util.MyPreferenceManager;
import inet.app.model.util.SmartLog;
import inet.app.model.util.Util;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;

public class FlashScreen extends Activity {

	private ImageView mSplashImg;

	boolean isRunning;
	int myYear, myMonth, myDay, myHour, myMinute;
	private Request request = new Request();
	private MasterConnector master;
	private String date_current, nhamang;
	// Loading
	private boolean finishLoading = false, successLoading = false;
	private int c = R.id.loading1, loadingTime = 0;
	private ImageView img1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.flash_screen);
		initSplashImg();
		((MyApp) getApplication()).setKill(false);
		GCMIntentService.registered(this,getResources().getString(R.string.app_name));

		nhamang = getOperatorName();
		Util.SharedPreferences(nhamang, FlashScreen.this);
		Util.savePreferences("quit", false, FlashScreen.this);
		Util.savePreferences("isPush", false, FlashScreen.this);
		resetPreference();
		Loading();
		Main();
		// Default Free
		MyPreferenceManager.getInstance(getApplicationContext()).setFree(false);
	}
	/**
	 * Load splash (large bitmap) from asynctask
	 */
	@SuppressWarnings("deprecation")
	private void initSplashImg() {
		mSplashImg = (ImageView) findViewById(R.id.splash_imgview);
		/* First, get the Display from the WindowManager */
		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();

		/* Now we can retrieve all display-related infos */

		int width = display.getWidth();
		int height = display.getHeight();

		BitmapLargeManager.getInstance(this).loadLargeBimap(
				R.drawable.manhinhcho, width, height, new LoadBitmapListener() {
					@Override
					public void onLoadFinish(int resId, boolean isSuccess) {
						if (isSuccess) {
							mSplashImg.setImageBitmap(BitmapLargeManager
									.getInstance(FlashScreen.this)
									.getBitmapFromCache(resId));
						} else {
							SmartLog.e("load splash image failed");
						}
					}
				});
	}

	protected void Main() {
		if (!Util.ketnoi(FlashScreen.this)) {
			// get kqxs from db
			if (isExistKQXSFromDB()) {
				Intent intent = new Intent(FlashScreen.this,
						KetQuaFragment.class);
				Bundle rb = new Bundle();
				rb.putString("json", XoSoConstants.GET_KQXS_FROM_DB);
				intent.putExtras(rb);
				startActivity(intent);
				finish();
			} else {
				showDialog(0, FlashScreen.this); // loi ket noi
			}
			return;
		}

		// connected
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if (msg.what == 0) {
					finishLoading = true;
					successLoading = true;
					String json = (String) msg.obj;
					Intent intent = new Intent(FlashScreen.this,KetQuaFragment.class);
					Bundle rb = new Bundle();
					rb.putString("json", json);
					intent.putExtras(rb);
					startActivity(intent);
					finish();
				} else if (msg.what == 1) {
					// du lieu dang cap nhat
					Util.showDialog(1, FlashScreen.this);
				} else {
					// loi ket noi
					Util.showDialog(0, FlashScreen.this);
				}
			}
		};

		Thread thread = new Thread() {
			public void run() {
				master = new MasterConnector(XoSoConstants.IP,XoSoConstants.PORT);
				boolean isConnectSlave = false;
				if (master.connect()) {
					String response = master.getRequest(Request_Format.Slave_Req("10000"));
					Parser_Slave_Resp parser = new Parser_Slave_Resp();
					Slave slave = parser.parser(response);
					if (slave != null) {
						((MyApp) getApplication()).setIp(slave.getIp());
						((MyApp) getApplication()).setPort(slave.getPort());
						((MyApp) getApplication()).setAppid(slave.getAppid());
						
						master = new MasterConnector(((MyApp) getApplication()).getIp(),((MyApp) getApplication()).getPort());
						
//						if(master!=null){
//							String _result = master.getRequest(Request_Format.XsSync_Req("XSTT", "13/01/2014"));
//							System.out.println("MAsster data ==> " + _result );
//						}
						
						
						((MyApp) getApplication()).set_socket(master.get_socket());
						
						if (master.connect()) {
							isConnectSlave = true;
							if (Util.onBeforeLiveTime()) {
								date_current = DateProc.TimestampPlusDay2DDMMYYYY(DateProc.createTimestamp(), -1);
							} else {
								date_current = DateProc.Timestamp2DDMMYYYY(DateProc.createTimestamp());
							}

							JsonParser jParser = new JsonParser();

							// find result in db
							KqGiaiRegion regionMB = DatabaseManager
									.instance(FlashScreen.this)
									.getDaoKqXSRegion()
									.selectRow(date_current, "MB");

							if (regionMB != null) {

								// load kqxs mb from db
								SmartLog.d("load kqxs mb " + date_current
										+ " from database success");
								try {
									Thread.sleep(2000);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								Message msg = handler.obtainMessage(0,
										XoSoConstants.GET_KQXS_FROM_DB);
								handler.sendMessage(msg);
							} else {

								// load kqxs mb from server
								SmartLog.d("load kqxs mb " + date_current
										+ " from server");
								String jobject = jParser.getURL(request
										.getkqxsbyregion(date_current, "MB"));
								String dttt = jParser.getURL(request
										.getxsdttt(date_current));
								String json = jobject + "_____" + dttt;

								if (jobject != null) {
									KqGiaiRegion region = new KqGiaiRegion();
									region.setDate(date_current);
									region.setRegion("MB");

									if (!Util.onLiveTime_MB()) {
										DatabaseManager
												.instance(FlashScreen.this)
												.getDaoKqXSRegion()
												.insertRow(region);
									}

									try {
										Thread.sleep(2000);
									} catch (InterruptedException e) {
										e.printStackTrace();
									}
									Message msg = handler
											.obtainMessage(0, json);
									handler.sendMessage(msg);
								} else {
									Message msg = handler.obtainMessage(1);
									handler.sendMessage(msg);
								}
							}
						}
					}
				}

				// can't connect slave
				if (!isConnectSlave) {
					Message msg = handler.obtainMessage(2); // loi ket noi
					handler.sendMessage(msg);
				}
			}
		};
		thread.start();
	}

	private boolean isExistKQXSFromDB() {

		return DatabaseManager.instance(this).getDaoKqXSRegion()
				.isExistData(DBConfig.TABLE_KQGIAI_REGION);
	}

	public void showDialog(int i, final Activity act) {
		AlertDialog.Builder builder = new AlertDialog.Builder(act);
		builder.setTitle("Thông báo");
		if (i == 0)
			builder.setMessage(R.string.error_connect);
		if (i == 1)
			builder.setMessage(R.string.error_response);
		builder.setPositiveButton("Đóng cửa sổ",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				});
		builder.show();
	}

	private String getOperatorName() {
		TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		String carrierName = manager.getNetworkOperatorName();
		return carrierName;
	}

	private void resetPreference() {
		MyPreferenceManager mPreference = MyPreferenceManager.getInstance(this);
		Util.savePreferences(XoSoConstants.GET_SOMO_FROM_DB, false, this);
		mPreference.setLoadTKDB(XoSoConstants.PREFERENCE_TKDB_BO, false);
		mPreference.setLoadTKDB(XoSoConstants.PREFERENCE_TKDB_DAU, false);
		mPreference.setLoadTKDB(XoSoConstants.PREFERENCE_TKDB_DUOI, false);
		mPreference.setLoadTKDB(XoSoConstants.PREFERENCE_TKDB_TONG, false);
	}

	private void Loading() {
		// TODO Auto-generated method stub
		img1 = (ImageView) findViewById(R.id.loading1);
		img1.setImageResource(R.drawable.loading_w);
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					int i1 = (Integer) msg.obj;
					ImageView i = (ImageView) findViewById(i1);
					i.setImageResource(R.drawable.loading_w);
				} else if (msg.what == 2) {
					int i2 = (Integer) msg.obj;
					ImageView i = (ImageView) findViewById(i2);
					i.setImageResource(R.drawable.loading_y1);
				} else if (msg.what == 0) {
					System.out.println("CHAY VAO 0");
				} else if (msg.what == -1) {
					System.out.println("CHAYJ VAO DAY 1");
				}
				super.handleMessage(msg);
			}
		};

		Thread t = new Thread() {
			public void run() {
				long c1 = System.currentTimeMillis();
				while (finishLoading == false || loadingTime < 3000) {
					int i = getNextLoading(c);
					try {
						Thread.sleep(200);
						loadingTime += 200;
						Message msg1 = handler.obtainMessage(1, i);
						handler.sendMessage(msg1);
						Message msg2 = handler.obtainMessage(2, c);
						handler.sendMessage(msg2);
						c = i;
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				long c2 = System.currentTimeMillis();

				if (c2 - c1 < 3000)
					try {
						Thread.sleep((c2 - c1));
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				if (successLoading == true) {
					Message msg0 = handler.obtainMessage(0);
					handler.sendMessage(msg0);
				} else {
					Message msg1 = handler.obtainMessage(-1);
					handler.sendMessage(msg1);
				}
			}
		};
		t.start();

	}

	protected int getNextLoading(int cc) {
		if (cc == R.id.loading1)
			return R.id.loading2;
		else if (cc == R.id.loading2)
			return R.id.loading3;
		else if (cc == R.id.loading3)
			return R.id.loading4;
		else if (cc == R.id.loading4)
			return R.id.loading5;
		else
			return R.id.loading1;
	}

	@Override
	public void onResume() {
		if (((MyApp) getApplication()).isKill()) {
			finish();
		} else {
			((MyApp) getApplication()).setRunning(true);
		}
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		BitmapLargeManager.getInstance(getApplicationContext()).removeBitmap(
				R.drawable.manhinhcho);
	}

}
